//https://blog.csdn.net/zl1zl2zl3/article/details/81357146
import React, {
	PureComponent,
	Fragment
} from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { getNodeByNameAndCallbackProcess } from '@/components/_utils/algorithmTools';
import {
	Row,
	Col,
	Card,
	Form,
	Input,
	Select,
	Icon,
	Button,
	Modal,
	message,
	Divider,
	Table,
	DatePicker
} from 'antd';
//import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import SelectPoliceRankTree from '@/components/SelectPoliceRankTree';
import SelectDutyLevelTree from '@/components/SelectDutyLevelTree';
import SelectWorkTree from '@/components/SelectWorkTree';
import SelectChangeTypeTree from '@/components/SelectChangeTypeTree';
import styles from './ProPersonSearchList.less';
import {getValue} from '@/utils/globalcommon';
import {initTotalList} from '@/utils/globalcommon';
import approveStatic from '@/assets/approve_static.png';
import printJS from 'print-js';
import ExportJsonExcel from 'js-export-excel';
const FormItem = Form.Item;
const { Option } = Select;
const { confirm } = Modal;
const { RangePicker } = DatePicker;
//用户列表

class StandardTable extends PureComponent {

  constructor(props) {
    super(props);
    const { columns } = props;
    const needTotalList = initTotalList(columns);

    this.state = {
      selectedRowKeys: [],
      needTotalList,
    };
  }

  static getDerivedStateFromProps(nextProps) {
    // clean state
    if (nextProps.selectedRows.length === 0) {
      const needTotalList = initTotalList(nextProps.columns);
      return {
        selectedRowKeys: [],
        needTotalList,
      };
    }
    return null;
  }

  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    let { needTotalList } = this.state;
    needTotalList = needTotalList.map(item => ({
      ...item,
      total: selectedRows.reduce((sum, val) => sum + parseFloat(val[item.dataIndex], 10), 0),
    }));
    const { onSelectRow } = this.props;
    if (onSelectRow) {
      onSelectRow(selectedRows);
    }

    this.setState({ selectedRowKeys, needTotalList });
  };

  handleTableChange = (pagination, filters, sorter) => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(pagination, filters, sorter);
    }
  };

  cleanSelectedKeys = () => {
    this.handleRowSelectChange([], []);
  };

  render() {
    const { selectedRowKeys, needTotalList } = this.state;
    const { data = {}, rowKey, ...rest } = this.props;
    const { list = [], pagination } = data;

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      current:pagination? pagination.currentPage : 1,
      ...pagination,
    };

    const rowSelection = {
      selectedRowKeys,
      onChange: this.handleRowSelectChange,
      getCheckboxProps: record => ({
        disabled: record.disabled,
      }),
    };

    return (
      <div className={styles.standardTable}>
        <Table
          rowKey={rowKey || 'key'}
          rowSelection={rowSelection}
          dataSource={list}
          pagination={paginationProps}
          onChange={this.handleTableChange}
          {...rest}
          size="middle"
          scroll={{x: 'max-content'}}
        />
      </div>
    );
  }
}

/* eslint react/no-multi-comp:0 */
@connect(({
	personsearch,
	loading
}) => ({
	personsearch,
	loading: loading.models.personsearch,
}))

@Form.create()
class ProApproveStaticList extends PureComponent {
	state = {
		modalVisible: false,
		updateModalVisible: false,
		viewModalVisible: false,
		expandForm: false,
		selectedRows: [],
		formValues: {},
		updateFormValues: {},
		viewFormValues: {},
		requestModelName:"personsearch",
		currentPage: 1,
		pageSize: 10,
    modalVisibleByCommand: false,
    modalVisibleByPoliceSave: false
	};

  //查看命令
  handleModalVisibleByCommand = flag => {
  		this.setState({
  			modalVisibleByCommand: !!flag,
  		});

  };

  //查看存档
  handleModalVisibleByPoliceSave = flag => {
  		this.setState({
  			modalVisibleByPoliceSave: !!flag,
  		});

  };

	columns = [
        {
	        title: '姓名',
	        dataIndex: 'name',
	        key: 'name',
        },  {
	        title: '性别',
	        dataIndex: 'sex',
	        key: 'sex',
        }, 	{
	        title: '年龄',
	        dataIndex: 'age',
	        key: 'age',
        },  {
	        title: '警号',
	        dataIndex: 'police_num',
	        key: 'police_num',
        }, {
	        title: '民族',
	        dataIndex: 'nation',
	        key: 'nation',
        },{
	        title: '工作单位',
	        dataIndex: 'unit',
	        key: 'unit',
        },{
	        title: '参加工作时间',
	        dataIndex: 'appointment_time',
	        key: 'appointment_time',
        },{
	        title: '政治面貌',
	        dataIndex: 'politic',
	        key: 'politic',
        },{
	        title: '现任职级',
	        dataIndex: 'duty_level',
	        key: 'duty_level',
        },{
	        title: '现任衔称',
	        dataIndex: 'police_rank',
	        key: 'police_rank',
        },{
	        title: '最高学历',
	        dataIndex: 'educational',
	        key: 'educational',
        },{
          title: '操作',
          fixed:'right',
          align: 'center',
          width: 160,
          render: (text, record) => {
	        	return (
		        	<Fragment>
                  <a onClick={() => this.handleModalVisibleByCommand(true)}>查看命令</a>
                  <Divider type="vertical" />
                  <a onClick={() => this.handleModalVisibleByPoliceSave(true)}>查看存档</a>
              </Fragment>
	        	);
          }
        }
	];

	componentDidMount() {
		const { dispatch } = this.props;
		dispatch({
			type: 'personsearch/query_page_for_personsearch',
		});
	}

	handleStandardTableChange = (pagination, filtersArg, sorter) => {
		const { dispatch } = this.props;
		const { formValues } = this.state;

		this.setState({
			currentPage: pagination.current,
			pageSize: pagination.pageSize,
			selectedRows: [],
		})

		const filters = Object.keys(filtersArg).reduce((obj, key) => {
			const newObj = { ...obj
			};
			newObj[key] = getValue(filtersArg[key]);
			return newObj;
		}, {});

		const params = {
			currentPage: pagination.current,
			pageSize: pagination.pageSize,
			...formValues,
			...filters,
		};
		if(sorter.field) {
			params.sorter = `${sorter.field}_${sorter.order}`;
		}

		dispatch({
			type: 'personsearch/query_page_for_personsearch',
			payload: params,
		});
	};

	previewItem = id => {
		router.push(`/profile/basic/${id}`);
	};

	handleFormReset = () => {
		const { form,dispatch } = this.props;
		form.resetFields();
		this.setState({
				formValues: {},
				currentPage:1,
				selectedRows: [],
		});
		dispatch({
			type: 'personsearch/query_page_for_personsearch',
		});
	};

	toggleForm = () => {
		const { expandForm } = this.state;
		this.setState({
			expandForm: !expandForm,
		});
	};


	handleSelectRows = rows => {
		this.setState({
			selectedRows: rows,
		});
	};

	handleSearch = e => {
		e.preventDefault();

		const {
			dispatch,
			form
		} = this.props;

		form.validateFields((err, fieldsValue) => {
			if(err) return;

			const values = {
				...fieldsValue,
				updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
			};

			this.setState({
				currentPage:1,
				selectedRows: [],
				formValues: values,
			});

			dispatch({
				type: 'personsearch/query_page_for_personsearch',
				payload: values,
			});
		});
	};

	handleModalVisible = flag => {
		this.setState({
			modalVisible: !!flag,
		});
	};

	handleUpdateModalVisible = (flag, record) => {
		this.setState({
			updateModalVisible: !!flag,
			updateFormValues: record || {},
		});
	};

	handleViewModalVisible = (flag, record) => {
		this.setState({
			viewModalVisible: !!flag,
			viewFormValues: record || {},
		});
	};

	handleAdd = fields => {
		const { dispatch } = this.props;

		dispatch({
			type: 'prouser/insert_for_prouser',
			payload: {
				user_name: fields.user_name,
				user_name_cn: fields.user_name_cn,
				password: fields.password,
				email: fields.email,
				phone: fields.phone,
				auth_ids: fields.auth_ids,
				dept_id: fields.dept_id,
				dept: fields.dept,
				post_id: fields.post_id,
				post_name: fields.post_name,
				enabled: fields.enabled,

				is_system_user: fields.is_system_user,
				creator_id: fields.creator_id,
				inner_dept_code: fields.inner_dept_code,
				org_code: fields.org_code,
				org: fields.org,
				inner_org_code: fields.inner_org_code,
				memos: fields.memos,
				avatar: fields.avatar,
				job: fields.job,
				createTime: fields.createTime,
			},
			callback:(res) => {
	        	if(res.success) {
					message.success('添加成功');
	        	}else {
        			message.success('添加失败');
	        	}
  			}
		});

		this.setState({
				selectedRows: [],
		});

		this.handleModalVisible();

	};


	handleUpdate = fields => {

		const { dispatch } = this.props;
		const { currentPage,pageSize } = this.state;
		dispatch({
			type: 'prouser/update_for_prouser',
			payload: {
				user_id: fields.user_id,
				user_name: fields.user_name,
				user_name_cn: fields.user_name_cn,
				password: fields.password,
				email: fields.email,
				phone: fields.phone,
				auth_ids: fields.auth_ids,
				dept_id: fields.dept_id,
				dept: fields.dept,
				post_id: fields.post_id,
				post_name: fields.post_name,
				enabled: fields.enabled,
				currentPage,
        		pageSize
			},
			callback:(res) => {
	        	if(res.success) {
					message.success('修改成功');
	        	}else {
        			message.success('修改失败');
	        	}
      		}
		});

		this.setState({
			selectedRows: [],
		});

		this.handleUpdateModalVisible();

	};

	handleDeleteRecord = record => {
		const { dispatch } = this.props;
		const { currentPage,pageSize } = this.state;
		confirm({
	    title: '您确定要删除此项吗?',
	    okText: '确认',
	    cancelText: '取消',
	    onOk() {

	    },
	    onCancel() {},
	  });

	  this.setState({
			selectedRows: [],
	   });

	};
	//拟授警衔
	selectedPoliceRankTreeValue = (deptRecord) => {
		  this.setState({
  			getPoliceRankTreeBySelectTree: deptRecord,
  		})
	}

	//职务层次
	selectedDutyLevelTreeValue = (deptRecord) => {
		  this.setState({
  			getDutyLevelTreeBySelectTree: deptRecord,
  		})
	}

	//单位
	selectedWorkTreeValue = (deptRecord) => {
		  this.setState({
  			getWorkTreeBySelectTree: deptRecord,
  		})
	}

	//变动类型
	selectedChangeTypeTreeValue = (deptRecord) => {
		  this.setState({
  			getChangeTypeTreeBySelectTree: deptRecord,
  		})
	}


  //打印
  print = () => {
    printJS({
      printable: 'print',
      type: 'html'
    });
  }

  //导出excel
  downloadExl = () => {
    	var option={};
    	let dataTable = [];
  	  option.fileName = '警衔审批统计表'
  	  option.datas=[
  	    {
  	      sheetData:dataTable,
  	      sheetName:'警衔审批统计表',
  	      sheetHeader:['左括号','信息项','关系','查询值','右括号','逻辑符'],
  	      columnWidths: [10,10,10,10,10,10],
  	      columnHeights: [10,10,10,10,10,10]
  	    }
  	  ];

  	  var toExcel = new ExportJsonExcel(option);
  	  toExcel.saveExcel();
  }

	renderSimpleForm() {
		const {
			form: {
				getFieldDecorator
			},
			personsearch: {
				selectPoliceRankTree
			},
		} = this.props;
		const parentPoliceRankTreeMethod = {
			dispatch: this.props.dispatch,
			requestModelName: this.state.requestModelName,
			selectedPoliceRankTreeValue: this.selectedPoliceRankTreeValue,
			selectPoliceRankTree,
			resetFlag: this.state.resetFlag
		}
		return(
		<Form onSubmit={this.handleSearch} layout="inline">
	      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col md={8} sm={24}>
                <FormItem label="单位">
                  {getFieldDecorator('unit')(<Input placeholder="请输入" />)}
            </FormItem>
            </Col>
            <Col md={8} sm={24}>
                <FormItem label="审批时间">
                  {getFieldDecorator('starttime')(
                    <RangePicker format={"YYYY-MM-DD"} style={{ width: '100%' }} placeholder={['开始时间', '结束时间']} />
                  )}
              </FormItem>
            </Col>
			    <Col md={8} sm={24}>
			        <span className={styles.submitButtons}>
			        <Button type="primary" htmlType="submit">
			        	查询
			        </Button>
			        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
			        	重置
			        </Button>
			        </span>
		        </Col>
	        </Row>
	      </Form>
		);
	}

	renderAdvancedForm() {
		const {
			form: {
				getFieldDecorator
			},
			personsearch: {
				selectPoliceRankTree,
				selectDutyLevelTree,
				selectWorkTree,
				selectChangeTypeTree,
			},
		} = this.props;



		const parentPoliceRankTreeMethod = {
			dispatch: this.props.dispatch,
			requestModelName: this.state.requestModelName,
			selectedPoliceRankTreeValue: this.selectedPoliceRankTreeValue,
			selectPoliceRankTree,
			resetFlag: this.state.resetFlag
		}
		const parentDutyLevelTreeMethod = {
			dispatch: this.props.dispatch,
			requestModelName: this.state.requestModelName,
			selectedDutyLevelTreeValue: this.selectedDutyLevelTreeValue,
			selectDutyLevelTree,
			resetFlag: this.state.resetFlag
		}
		const parentWorkTreeMethod = {
			dispatch: this.props.dispatch,
			requestModelName: this.state.requestModelName,
			selectedWorkTreeValue: this.selectedWorkTreeValue,
			selectWorkTree,
			resetFlag: this.state.resetFlag
		}
		const parentChangeTypeTreeMethod = {
			dispatch: this.props.dispatch,
			requestModelName: this.state.requestModelName,
			selectedChangeTypeTreeValue: this.selectedChangeTypeTreeValue,
			selectChangeTypeTree,
			resetFlag: this.state.resetFlag
		}
		return(
			<Form onSubmit={this.handleSearch} layout="inline">
		      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
							<Col md={8} sm={24}>
						        <FormItem label="姓名">
						        	{getFieldDecorator('name')(<Input placeholder="请输入" />)}
								</FormItem>
						    </Col>
					      <Col md={8} sm={24}>
						        <FormItem label="现任警衔">
						        	{getFieldDecorator('police_rank')(<SelectPoliceRankTree  {...parentPoliceRankTreeMethod}/>)}
										</FormItem>
					    	</Col>
					      <Col md={8} sm={24}>
						        <FormItem label="职务层次">
						        	{getFieldDecorator('duty_level')(<SelectDutyLevelTree  {...parentDutyLevelTreeMethod}/>)}
										</FormItem>
					    	</Col>
		    	</Row>
		      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
				      <Col md={8} sm={24}>
						        <FormItem label="单位">
						        	{getFieldDecorator('company')(<SelectWorkTree  {...parentWorkTreeMethod}/>)}
								</FormItem>
					    	</Col>
				      <Col md={8} sm={24}>
						        <FormItem label="变动类型">
						        	{getFieldDecorator('change_type')(<SelectChangeTypeTree  {...parentChangeTypeTreeMethod}/>)}
										</FormItem>
					    	</Col>
					    <Col md={8} sm={24}>
				        <FormItem label="人员记录">
				            {getFieldDecorator('ryjl')(
				                <Select placeholder="请选择" style={{ width: '100%' }}>
				                    <Option value="1">全部</Option>
				                    <Option value="0">重复</Option>
				                </Select>
				            )}
				        </FormItem>
			        </Col>
		    	</Row>
			    <div style={{ overflow: 'hidden' }}>
					<div style={{ marginBottom: 24 }}>
					<Button type="primary" htmlType="submit">
			        查询
			        </Button>
			        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
			        重置
			        </Button>
			        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
			        收起 <Icon type="up" />
			        </a>
		        	</div>
		        </div>
	      </Form>
		);
	}

	renderForm() {
		const {
			expandForm
		} = this.state;

		return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
	}

	render() {
		const {
			personsearch: {
				data,
				authForUser,
				postForUser
			},
			loading,
		} = this.props;

		const {
			selectedRows,
			modalVisible,
			updateModalVisible,
			viewModalVisible,
			updateFormValues,
			viewFormValues,
			addButtonVisible,
      modalVisibleByCommand,
      modalVisibleByPoliceSave
		} = this.state;

    //查看命令
    const parentMethodsByCommand = {
    	handleModalVisibleByCommand: this.handleModalVisibleByCommand,
    	modalVisibleByCommand
    };

    //查看存档
    const parentMethodsByPoliceSave = {
    	handleModalVisibleByPoliceSave: this.handleModalVisibleByPoliceSave,
    	modalVisibleByPoliceSave
    };

		const parentMethods = {
			handleAdd: this.handleAdd,
			handleModalVisible: this.handleModalVisible,
			dispatch: this.props.dispatch,
			requestModelName: this.state.requestModelName,
			authForUser,
			postForUser
		};
		const updateMethods = {
			handleUpdateModalVisible: this.handleUpdateModalVisible,
			handleUpdate: this.handleUpdate,
			dispatch: this.props.dispatch,
			requestModelName: this.state.requestModelName,
			authForUser,
			postForUser
		};
		const viewMethods = {
			handleViewModalVisible: this.handleViewModalVisible
		};
		return(
			<PageHeaderWrapper title="警衔审批统计表">
      <Card bordered={false}>
            <div className={styles.proUsertableList}>
            <div className={styles.proUsertableListForm}>{this.renderForm()}</div>
            <div className={styles.proUsertableListOperator}>
            <Button icon="printer" type="primary" onClick={this.print}>
                打印
            </Button>
            <Button icon="download" type="primary"  style={{marginRight: '15px'}} onClick={this.downloadExl}>
                导出
            </Button>

      </div>
      <div style={{textAlign: 'center'}}>
        <img id="print"  alt="" src={approveStatic} style={{width: '85%'}}/>
      </div>

        </div>
        </Card>
    </PageHeaderWrapper>
		);
	}
}

export default ProApproveStaticList;
